package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Good;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.GoodMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.Result;
import com.sky.service.ShoppingCartService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.DeleteMapping;

import java.util.List;

@Slf4j
@Service
public class ShoppingCartServiceImpl  implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private GoodMapper goodMapper;

    @Override
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {

        Good good = goodMapper.getById(shoppingCartDTO.getGoodId());
        // 检查商品是否存在
        if (good == null) {
            // 在实际应用中，这里应该抛出自定义的业务异常，例如 GoodNotFoundException
            throw new RuntimeException("商品不存在，无法添加到购物车");
        }
        // 创建 ShoppingCart 对象并复制属性
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);

        // 设置当前用户 ID
        shoppingCart.setUserId(BaseContext.getCurrentId());

        // 判断当前商品是否已存在于购物车中
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);

        if (shoppingCartList != null && !shoppingCartList.isEmpty()) {
            // 如果存在，更新数量 +1
            ShoppingCart existingCart = shoppingCartList.get(0);
            existingCart.setNumber(existingCart.getNumber() + 1);
            shoppingCartMapper.updateNumberById(existingCart);
        } else {
            shoppingCart.setName(good.getName());
            shoppingCart.setImage(good.getImage());
            log.info("当前用户id:{}",BaseContext.getCurrentId());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setDishId(shoppingCartDTO.getGoodId());
            // 如果不存在，插入新记录，数量设为 1
            shoppingCart.setNumber(1);
            shoppingCart.setAmount(good.getPrice());

            shoppingCartMapper.insert(shoppingCart);
        }
    }

    @Override
    public List<ShoppingCart> showShoppingCart() {
        return shoppingCartMapper.list(ShoppingCart.
                builder().
                userId(BaseContext.getCurrentId()).
                build());
    }

    /**
     * 清空购物车商品
     */
    public void cleanShoppingCart() {
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
    }

}
